import axios from 'axios';
import { message as Message } from '@/utils/resetMessage';
import store from '@/store';
import { removeToken } from '@/utils/auth';
import router from '@/router';

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
});

// request interceptor
service.interceptors.request.use(
  config => {
    const token = store.getters.token;
    config.headers['Authorization'] = token;
    return config;
  },
  error => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  response => {
    if (response.status === 200) {
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  error => {
    // 请求超时拦截
    console.error(error);
    if (error.message.includes('timeout')) {
      Message.error({
        message: '网络请求超时'
      });
      return Promise.reject(error);
    }
    if (error.response.status) {
      switch (error.response.status) {
        case 401:
          console.log(401);
          removeToken();
          store.commit('user/SET_TOKEN', null);
          Message.error({
            message: '401身份无效'
          });
          router.replace({ path: '/login' });
          break;
        case 404:
          console.log(404);
          Message.error({
            message: '404网络错误'
          });
          break;
        case 500:
          console.log(500);
          Message.error({
            message: '500服务器异常'
          });
          break;
        case 504:
          console.log(504);
          Message.error({
            message: '504网关超时'
          });
          break;
      }
    }
    return Promise.reject(error);
  }
);

export default service;
